<template>
  <el-dialog
    v-model="visible"
    :title="form.shopSeckillId ? visitDetail ? '查看秒杀活动' : '修改秒杀活动' : '新增秒杀活动'"
    class="addGroupBuy"
    width="700px"
    center
    top="10vh"
    :close-on-click-modal="false"
    @close="close"
  >
    <div class="addGroupBuyBox">
      <el-form
        ref="formRef"
        class="formBox"
        :model="form"
        label-width="150px"
        :rules="rules"
        :disabled="visitDetail"
      >
        <el-form-item label="活动名称" prop="seckillName">
          <el-input
            v-model="form.seckillName"
            maxlength="15"
            placeholder="请输入活动名称"
            style="width: 500px;"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            maxlength="200"
            placeholder="请输入备注"
            style="width: 500px;"
          />
        </el-form-item>
        <el-form-item label="活动时间" prop="activityDate">
          <el-date-picker
            v-model="dateInfo"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item class="boxWidth" label="商品限购" prop="ifLimit">
          <el-radio-group v-model="form.ifLimit" class="comRadio">
            <el-radio :label="1">不限购</el-radio>
            <el-radio :label="2">限购</el-radio>
          </el-radio-group>
          &nbsp;
          <el-input
            v-model="form.limitNumber"
            maxlength="9"
            :disabled="form.ifLimit === 1"
            oninput="value=value.replace(/[^\d]/g,'')"
            style="width: 100px;"
          />&nbsp;件/人
        </el-form-item>
        <el-form-item label="活动商品限量" prop="ifNumber">
          <el-radio-group v-model="form.ifNumber" class="comRadio">
            <el-radio :label="0">不限量</el-radio>
            <el-radio :label="1">限量</el-radio>
          </el-radio-group>
          &nbsp;
          <el-input
            v-model="form.number"
            maxlength="9"
            :disabled="form.ifNumber === 0"
            oninput="value=value.replace(/[^\d]/g,'')"
            style="width: 100px;"
          />&nbsp;件
        </el-form-item>
        <el-form-item label="活动预热" prop="ifEnable">
          <el-radio-group v-model="form.ifEnable" class="comRadio">
            <el-radio :label="1">停用</el-radio>
            <el-radio :label="2">启用</el-radio>
          </el-radio-group>
          &nbsp;
          <el-input
            v-model="form.enableTime"
            maxlength="9"
            :disabled="form.ifEnable === 1"
            oninput="value=value.replace(/[^\d]/g,'')"
            style="width: 100px;"
          />&nbsp;小时前
        </el-form-item>
        <el-form-item label="优惠券叠加" prop="ifAdd">
          <el-radio-group v-model="form.ifAdd" class="comRadio">
            <el-radio :label="1">叠加</el-radio>
            <el-radio :label="0">不叠加</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="applyType" label="活动商品" prop="commodity">
          <span
            class="selectBtn"
            @click="chooseProduct"
          ><span v-if="!visitDetail">请选择</span><span v-else>查看商品</span><i v-if="form.details.length !== 0" class="selectNum">{{
            form.details.length
          }}</i></span>
        </el-form-item>
      </el-form>
    </div>
    <span class="dialog-footer">
      <el-button
        v-show="!visitDetail"
        type="primary"
        @click="seckillSubmit"
      >保 存</el-button>
      <!--      <el-button v-if="visitDetail" type="primary" @click="goToSpike">取 消</el-button>-->
      <el-button type="danger" @click="goToSpike">取 消</el-button>
    </span>
    <!-- 商品 -->
    <el-dialog
      v-model="productVisible"
      :title="visitDetail ? '查看商品' : '选择商品'"
      width="58%"
      top="50px"
      class="group-dialog"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :modal="false"
    >
      <!-- 表格 -->
      <div class="tableBox">
        <el-table
          ref="multipleTableRef"
          :data="productData"
          border
          :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
          tooltip-effect="dark"
          style="width: 100%"
          row-key="skuId"
          max-height="600"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            v-if="!visitDetail"
            type="selection"
            :reserve-selection="true"
            width="55"
          />
          <el-table-column label="商品信息" width="150" align="center">
            <template #default="scope">
              <img height="80" width="80" :src="scope.row.image" alt srcset />
            </template>
          </el-table-column>
          <el-table-column prop="productName" label="" />
          <el-table-column
            prop="originalPrice"
            label="原价（元）"
            width="120"
          />
          <el-table-column prop="value" label="规格" width="120" />
          <el-table-column label="直降（元）" width="153">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.downPrice"
                :disabled="visitDetail"
                size="small"
                :controls="false"
                :max="scope.row.originalPrice - 0.01"
                :min="0.01"
                :precision="2"
                @input.native="changeCode(scope.row)"
                @blur="blurInput(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="秒杀价（元）" width="150">
            <template #default="scope">
              <span v-if="scope.row.downPrice">{{
                (scope.row.originalPrice - scope.row.downPrice).toFixed(2)
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="stockNumber"
            label="库存"
            width="120"
            show-overflow-tooltip
          />
          <!--          <el-table-column width="80" label="操作" show-overflow-tooltip>-->
          <!--            <template #default="scope">-->
          <!--              <div class="btnList">-->
          <!--                <el-popconfirm title="确定删除此活动？" @onConfirm="deleteSeckillFn(scope.row)">-->
          <!--                  <el-button slot="reference" class="delCls" type="text">删除</el-button>-->
          <!--                </el-popconfirm>-->
          <!--              </div>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
        </el-table>
        <div class="fenye">
          <el-pagination
            :current-page="formInline.page"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="formInline.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
      <template #footer>
        <div class="footBtnBox">
          <span>
            <el-button
              v-if="!visitDetail"
              type="primary"
              @click="saveIdList"
            >确 定</el-button>
            <el-button @click="closeSelect">取 消</el-button>
          </span>
        </div>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import {
  addSeckill,
  getSpikeList,
  seckillUpdate,
  seckillDetail,
} from '@/api/marketing'
import { nextTick, ref } from 'vue';

const emit = defineEmits(['reset'])

defineExpose({
  open, close
})

/**
 * @property {null | number} shopSeckillId 秒杀活动id
 * @property {null | number} seckillName 秒杀活动名称
 * @property {null | number} remark 备注
 * @property {null | number} details 商品明细数据
 * @property {null | number} ifEnable 秒杀活动预热 1-停用 2-启用
 * @property {null | number} enableTime 预热几小时前
 * @property {null | number} effectiveStart 活动开始时间
 * @property {null | number} effectiveEnd 秒杀活动结束时间
 * @property {null | number} ifAdd 优惠券是否叠加 1-是 0-否
 * @property {null | number} ifLimit 商品限购 1-不限购 2-限购
 * @property {null | number} limitNumber 限购几件/人
 * @property {null | number} person 成团人数
 * @property {null | number} ifNumber 是否限量
 * @property {null | number} number 限制数量
 */
function initForm (data) {
  return {
    shopSeckillId: data && data.shopSeckillId || null,
    seckillName: data && data.seckillName || '',
    details: data && data.details || [],
    ifEnable: data && data.ifEnable || 1,
    enableTime: data && data.enableTime || '',
    effectiveStart: data && data.effectiveStart || '',
    effectiveEnd: data && data.effectiveEnd || '',
    ifAdd: data && data.ifAdd || 1,
    ifLimit: data && data.ifLimit || 1,
    limitNumber: data && data.limitNumber || '',
    person: data && data.person || null,
    remark: data && data.remark || '',
    ifNumber: data && data.ifNumber || 0,
    number: data && data.number || null,
  }
}

const visible = ref(false)
const formRef = ref()
const visitDetail = ref(false)
const form = ref(initForm())
const productVisible = ref(false)
const formInline = ref({
  page: 1,
  pageSize: 10,
  activityId: null
})
const total = ref(0)
const productData = ref([])
const multipleTableRef = ref()
const multipleSelection = ref([])
const inputSpikeTableData = ref([])
const dateInfo = ref([])

const rules = {
  seckillName: [
    { required: true, message: '请输入活动名称', trigger: 'blur' },
  ],
  activityDate: [
    { required: true, validator: validDate, trigger: 'change' },
  ],
  ifLimit: [
    { validator: validLimit, trigger: 'change' },
  ],
  ifNumber: [
    { validator: validNumber, trigger: 'change' },
  ],
  ifEnable: [
    { validator: validEnable, trigger: 'change' },
  ],
  commodity: [
    { required: true, validator: validCommodity, trigger: 'change' },
  ]
}
function validDate (rule, value, callback) {
  if (!dateInfo.value || !dateInfo.value.length) {
    return callback(new Error('请选择活动时间'))
  }
  callback()
}
function validLimit (rule, value, callback) {
  if (form.value.ifLimit === 2 && !form.value.limitNumber) {
    return callback(new Error('请填写商品限购数量'))
  }
  callback()
}
function validNumber (rule, value, callback) {
  if (form.value.ifNumber === 1 && !form.value.number) {
    return callback(new Error('请选择活动商品数量'))
  }
  callback()
}
function validEnable (rule, value, callback) {
  if (form.value.ifEnable === 2 && !form.value.enableTime) {
    return callback(new Error('请填写活动预热时间'))
  }
  callback()
}
function validCommodity (rule, value, callback) {
  if (!form.value.details || !form.value.details.length) {
    return callback(new Error('请选择活动商品'))
  }
  callback()
}

function vildateForm (str) {
  if (str) {
    formRef.value.validateField(str)
  }
}

function open (id, isDetail) {
  form.value.shopSeckillId = id
  visitDetail.value = isDetail
  if (id) {
    getSeckillInfo()
  }
  visible.value = true
}
function close () {
  visible.value = false
  form.value = initForm()
  formInline.value.page = 1
  dateInfo.value = []
  inputSpikeTableData.value = []
  multipleTableRef.value?.clearSelection()
  formRef.value?.resetFields()
}

function getSeckillInfo () {
  seckillDetail({ shopSeckillId: form.value.shopSeckillId }).then(res => {
    form.value = initForm(res.data);
    form.value.effectiveTime = res.data.effectiveTime
    const idList = res.data.products
    idList.forEach((i) => {
      form.value.details.push({
        downPrice: i.downPrice,
        seckillPrice: i.originalPrice - i.downPrice,
        productId: i.productId,
        skuId: i.skuId,
      })
    })
    dateInfo.value = [form.value.effectiveStart, form.value.effectiveEnd]
  })
}

function blurInput (data) {
  const index = inputSpikeTableData.value.findIndex(
    (item) => item.skuId === data.skuId
  )
  if (index === -1) {
    inputSpikeTableData.value.push(data)
  } else {
    inputSpikeTableData.value[index].downPrice = data.downPrice
  }
}
function seckillSubmit () {
  formRef.value.validate((valid) => {
    if (valid) {
      form.value.effectiveStart = dateInfo.value[0]
      form.value.effectiveEnd = dateInfo.value[1]
      const fn = form.value.shopSeckillId ? seckillUpdate : addSeckill
      fn(form.value).then((res) => {
        if (res.code === '') {
          ElMessage.success('修改成功')
          form.value = initForm()
          dateInfo.value = []
          emit('reset')
        } else {
          ElMessage.error(res.message)
        }
      })
    }
  })
}
function changeCode (item) {
  nextTick(() => {
    if (item.downPrice >= item.originalPrice) {
      item.downPrice = item.originalPrice - 0.01
    }
  })
}

function getProList () {
  getSpikeList(formInline.value).then((res) => {
    if (res.code === '') {
      const dataList = res.data.list
      if (inputSpikeTableData.value.length > 0) {
        dataList.forEach((item) => {
          const index = inputSpikeTableData.value.findIndex(
            (cItem) => cItem.skuId === item.skuId
          )
          if (index !== -1) {
            item.downPrice = inputSpikeTableData.value[index].downPrice
          }
        })
      }
      productData.value = dataList
      total.value = res.data.total
    }
  })
}

function handleSizeChange (val) {
  formInline.value.pageSize = val
  getProList()
}
function handleCurrentChange (val) {
  formInline.value.page = val
  getProList()
}
// 选择商品
function chooseProduct () {
  productVisible.value = true
  formInline.value.activityId = visitDetail.value ? form.value.shopSeckillId : null
  getProList()
}
// 选中商品
function handleSelectionChange (val) {
  multipleSelection.value = val
}
// 保存选择商品ID
function saveIdList () {
  try {
    const idList = []
    multipleSelection.value.forEach((item) => {
      if (!item.downPrice) {
        ElMessage.warning('请输入价格')
        throw new Error()
      }
      idList.push({
        downPrice: item.downPrice,
        seckillPrice: item.originalPrice - item.downPrice,
        productId: item.productId,
        skuId: item.skuId,
      })
    })
    form.value.details = idList
    vildateForm('commodity');
    productVisible.value = false
  } catch (e) {
    console.log(e)
  }
}
// 取消选择
function closeSelect () {
  productVisible.value = false
}
// 跳转秒杀列表
function goToSpike () {
  emit('reset')
}

</script>

<style lang="scss" scoped>
.addGroupBuy {
  margin-top: 20px;
  background: #ffffff;
  .dialog-footer {
    display: flex;
    justify-content: center;
    .el-button {
      margin: 0px 16px;
    }
  }
  .formBox {
    margin-top: 20px;
    .flexBox {
      display: flex;
    }
    .applyType {
      span {
        width: 100px;
        height: 30px;
        line-height: 30px;
        background: #66b1ff;
        color: #ffffff;
        text-align: center;
        display: inline-block;
        font-size: 14px;
        margin-right: 30px;
        border-radius: 4px;
        cursor: pointer;
        position: relative;
        i {
          position: absolute;
          right: -10px;
          top: -10px;
          width: 25px;
          height: 25px;
          line-height: 25px;
          background: #ffffff;
          border-radius: 50%;
          border: 1px solid #66b1ff;
          text-align: center;
          color: #3A68F2;
          font-style: normal;
          font-size: 12px;
        }
      }
    }
  }
  .footBtnBox {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 50px;
  }
  .dateBox {
    display: flex;
    align-items: center;
    .description {
      width: 59px;
      text-align: center;
      display: block;
      font-size: 14px;
      color: #999999;
    }
  }
}
</style>

<style scoped>
:deep(.addGroupBuy) .el-button--primary {
  background: #3A68F2;
  border-color: #3A68F2;
}
:deep(.addGroupBuy) .el-dialog__header {
  background-color: #3A68F2;
}
:deep(.addGroupBuy) .el-dialog__headerbtn .el-dialog__close {
  color: #ffffff;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
input[type='number'] {
  -moz-appearance: textfield;
}
</style>
